const crypto = require("crypto")


function sha256(message, secret = "", encoding) {
	const hmac = crypto.createHmac("sha256", secret)
	return hmac.update(message).digest(encoding)
}

function getHash(message, encoding = "hex") {
	const hash = crypto.createHash("sha256")
	return hash.update(message).digest(encoding)
}

function getDate(timestamp) {
	const date = new Date(timestamp * 1000)
	const year = date.getUTCFullYear()
	const month = ("0" + (date.getUTCMonth() + 1)).slice(-2)
	const day = ("0" + date.getUTCDate()).slice(-2)
	return `${year}-${month}-${day}`
}

const SECRET_ID = "AKIDLmL0u1KyiUlVIDGzjjlyOsX9k4bKNUKO"
const SECRET_KEY = "XSVnDlP67W5eR6ovGj6UvPrIds4GTk3W"
const TOKEN = ""

const host = "asr.tencentcloudapi.com"
const service = "asr"
const region = "ap-guangzhou"
const action = "CreateRecTask"
const version = "2019-06-14"


let payload = "{}"




// asr服务生成签名
async function genBaseSignature(msg) {
	return new Promise((resolve, reject) => {
		const timestamp = parseInt(String(new Date().getTime() / 1000))
		const date = getDate(timestamp)

		const SignedHeaders = "content-type;host"
		const HTTPRequestMethod = "POST" //HTTP 请求方法（GET、POST ）
		const CanonicalURI = "/"
		const CanonicalQueryString = ""
		const CanonicalHeaders =
			"content-type:application/json; charset=utf-8\n" + "host:" + host + "\n"

		const algorithm = "TC3-HMAC-SHA256"
		const credentialScope = date + "/" + service + "/" + "tc3_request"

		if (msg) {
			payload = msg
		} else {
			payload = "{}"
		}
		payload = JSON.stringify(payload)
		// console.log("payload", payload)
		// ************* 步骤 1：拼接规范请求串 *************
		const HashedRequestPayload = getHash(payload)
		const canonicalRequest = HTTPRequestMethod + '\n' +
			CanonicalURI + '\n' +
			CanonicalQueryString + '\n' +
			CanonicalHeaders + '\n' +
			SignedHeaders + '\n' +
			HashedRequestPayload

		// ************* 步骤 2：拼接待签名字符串 *************
		const hashedCanonicalRequest = getHash(canonicalRequest)
		// console.log("HashedRequestPayload", HashedRequestPayload)
		const stringToSign = algorithm + '\n' + timestamp + '\n' + credentialScope + '\n' +
			hashedCanonicalRequest
		// ************* 步骤 3：计算签名 *************
		const kDate = sha256(date, "TC3" + SECRET_KEY)
		const kService = sha256(service, kDate)
		const kSigning = sha256("tc3_request", kService)
		const signature = sha256(stringToSign, kSigning, "hex")
		// ************* 步骤 4：拼接 Authorization *************
		const authorization =
			algorithm +
			" " +
			"Credential=" +
			SECRET_ID +
			"/" +
			credentialScope +
			", " +
			"SignedHeaders=" +
			SignedHeaders +
			", " +
			"Signature=" +
			signature

		// ************* 步骤 5：构造参数*************
		const headers = {
			Authorization: authorization,
			"Content-Type": "application/json; charset=utf-8",
			Host: host,
			"X-TC-Action": action,
			"X-TC-Timestamp": timestamp,
			"X-TC-Version": version,
		}

		if (region) {
			headers["X-TC-Region"] = region
		}

		if (TOKEN) {
			headers["X-TC-Token"] = TOKEN
		}
		resolve(headers)
	})

}


// 创建语音识别任务 
async function convertSpeechToText(signature) {
	return new Promise((resolve, reject) => {
		console.log(99999)
		uni.request({
			url: "https://asr.tencentcloudapi.com",
			method: 'POST',
			header: signature,
			data: payload,
			dataType: 'json',
			sslVerify:false,
			success: (response) => {
				console.log(66666, response)
				resolve(response.data);
			},
			fail: (error) => {
				console.error("6666,", error); // 请求失败的情况  
			}
		});
	});
}

// 查询任务结果
async function checkSpeechJob(TaskId, querySignature) {
	return new Promise((resolve, reject) => {
		querySignature["X-TC-Action"] = "DescribeTaskStatus"
		uni.request({
			url: `https://asr.tencentcloudapi.com`,
			method: 'POST',
			data: {
				TaskId: TaskId
			},
			header: querySignature,
			sslVerify:false,
			success: (response) => {
				resolve(response);
			},
			fail: (error) => {
				console.error(error); // 请求失败的情况  
			}
		});
	});

}


// tts服务生成签名
async function genTtsSignature(msg) {
	return new Promise((resolve, reject) => {
		const host = "tts.tencentcloudapi.com"
		const service = "tts"
		const region = "ap-guangzhou"
		const action = "TextToVoice"
		const version = "2019-08-23"

		const timestamp = parseInt(String(new Date().getTime() / 1000))
		const date = getDate(timestamp)

		const SignedHeaders = "content-type;host"
		const HTTPRequestMethod = "POST" //HTTP 请求方法（GET、POST ）
		const CanonicalURI = "/"
		const CanonicalQueryString = ""
		const CanonicalHeaders =
			"content-type:application/json; charset=utf-8\n" + "host:" + host + "\n"

		const algorithm = "TC3-HMAC-SHA256"
		const credentialScope = date + "/" + service + "/" + "tc3_request"

		if (msg) {
			payload = msg
		} else {
			payload = "{}"
		}
		payload = JSON.stringify(payload)
		// console.log("payload", payload)
		// ************* 步骤 1：拼接规范请求串 *************
		const HashedRequestPayload = getHash(payload)
		const canonicalRequest = HTTPRequestMethod + '\n' +
			CanonicalURI + '\n' +
			CanonicalQueryString + '\n' +
			CanonicalHeaders + '\n' +
			SignedHeaders + '\n' +
			HashedRequestPayload

		// ************* 步骤 2：拼接待签名字符串 *************
		const hashedCanonicalRequest = getHash(canonicalRequest)
		// console.log("HashedRequestPayload", HashedRequestPayload)
		const stringToSign = algorithm + '\n' + timestamp + '\n' + credentialScope + '\n' +
			hashedCanonicalRequest
		// ************* 步骤 3：计算签名 *************
		const kDate = sha256(date, "TC3" + SECRET_KEY)
		const kService = sha256(service, kDate)
		const kSigning = sha256("tc3_request", kService)
		const signature = sha256(stringToSign, kSigning, "hex")
		// ************* 步骤 4：拼接 Authorization *************
		const authorization =
			algorithm +
			" " +
			"Credential=" +
			SECRET_ID +
			"/" +
			credentialScope +
			", " +
			"SignedHeaders=" +
			SignedHeaders +
			", " +
			"Signature=" +
			signature

		// ************* 步骤 5：构造参数*************
		const headers = {
			Authorization: authorization,
			"Content-Type": "application/json; charset=utf-8",
			Host: host,
			"X-TC-Action": action,
			"X-TC-Timestamp": timestamp,
			"X-TC-Version": version,
		}

		if (region) {
			headers["X-TC-Region"] = region
		}

		if (TOKEN) {
			headers["X-TC-Token"] = TOKEN
		}
		resolve(headers)
	})

}

// tts服务长文本生成签名
async function genTtsLongSignature(msg) {
	return new Promise((resolve, reject) => {
		const host = "tts.tencentcloudapi.com"
		const service = "tts"
		const region = "ap-guangzhou"
		const action = "CreateTtsTask"
		const version = "2019-08-23"

		const timestamp = parseInt(String(new Date().getTime() / 1000))
		const date = getDate(timestamp)

		const SignedHeaders = "content-type;host"
		const HTTPRequestMethod = "POST" //HTTP 请求方法（GET、POST ）
		const CanonicalURI = "/"
		const CanonicalQueryString = ""
		const CanonicalHeaders =
			"content-type:application/json; charset=utf-8\n" + "host:" + host + "\n"

		const algorithm = "TC3-HMAC-SHA256"
		const credentialScope = date + "/" + service + "/" + "tc3_request"

		if (msg) {
			payload = msg
		} else {
			payload = "{}"
		}
		payload = JSON.stringify(payload)
		// console.log("payload", payload)
		// ************* 步骤 1：拼接规范请求串 *************
		const HashedRequestPayload = getHash(payload)
		const canonicalRequest = HTTPRequestMethod + '\n' +
			CanonicalURI + '\n' +
			CanonicalQueryString + '\n' +
			CanonicalHeaders + '\n' +
			SignedHeaders + '\n' +
			HashedRequestPayload

		// ************* 步骤 2：拼接待签名字符串 *************
		const hashedCanonicalRequest = getHash(canonicalRequest)
		// console.log("HashedRequestPayload", HashedRequestPayload)
		const stringToSign = algorithm + '\n' + timestamp + '\n' + credentialScope + '\n' +
			hashedCanonicalRequest
		// ************* 步骤 3：计算签名 *************
		const kDate = sha256(date, "TC3" + SECRET_KEY)
		const kService = sha256(service, kDate)
		const kSigning = sha256("tc3_request", kService)
		const signature = sha256(stringToSign, kSigning, "hex")
		// ************* 步骤 4：拼接 Authorization *************
		const authorization =
			algorithm +
			" " +
			"Credential=" +
			SECRET_ID +
			"/" +
			credentialScope +
			", " +
			"SignedHeaders=" +
			SignedHeaders +
			", " +
			"Signature=" +
			signature

		// ************* 步骤 5：构造参数*************
		const headers = {
			Authorization: authorization,
			"Content-Type": "application/json; charset=utf-8",
			Host: host,
			"X-TC-Action": action,
			"X-TC-Timestamp": timestamp,
			"X-TC-Version": version,
		}

		if (region) {
			headers["X-TC-Region"] = region
		}

		if (TOKEN) {
			headers["X-TC-Token"] = TOKEN
		}
		resolve(headers)
	})

}

// 发起短文本语音合成任务
async function shortTextToVoice(payload, signature) {
	return new Promise((resolve, reject) => {
		signature["X-TC-Action"] = "TextToVoice"
		signature["X-TC-Version"] = "2019-08-23"
		// console.log("payload2", payload)
		uni.request({
			url: `https://tts.tencentcloudapi.com`,
			method: 'POST',
			header: signature,
			data: payload,
			dataType: 'json',
			sslVerify:false,
			success: (response) => {
				// console.log("response", response)
				resolve(response.data);
			},
			fail: (error) => {
				console.error(error); // 请求失败的情况  
			}
		});
	});
}


// 创建长文本语音合成任务
async function longTextToVoice(signature) {
	return new Promise((resolve, reject) => {
		signature["X-TC-Action"] = "CreateTtsTask"
		signature["X-TC-Version"] = "2019-08-23"
		uni.request({
			url: `https://tts.tencentcloudapi.com`,
			method: 'POST',
			header: signature,
			data: payload,
			dataType: 'json',
			sslVerify:false,
			success: (response) => {
				resolve(response.data);
			},
			fail: (error) => {
				console.error(error); // 请求失败的情况  
			}
		});
	});
}

// 查询长文本语音合成任务结果
async function checkVoiceJob(TaskId, querySignature) {
	return new Promise((resolve, reject) => {
		querySignature["X-TC-Action"] = "DescribeTtsTaskStatus"
		querySignature["X-TC-Version"] = "2019-08-23"
		uni.request({
			url: `https://tts.tencentcloudapi.com`,
			method: 'POST',
			data: {
				TaskId: TaskId
			},
			header: querySignature,
			sslVerify:false,
			success: (response) => {
				resolve(response);
			},
			fail: (error) => {
				console.error(error); // 请求失败的情况  
			}
		});
	});

}



export {
	genBaseSignature,
	genTtsSignature,
	shortTextToVoice,
	checkSpeechJob,
	convertSpeechToText,
	genTtsLongSignature,
	longTextToVoice,
	checkVoiceJob
}